<template>
  <div class="app-container">
    <div class="public-account-management clearfix" v-loading="saveLoading">
      <!--左边配置菜单-->
      <div class="left">
        <div class="weixin-hd">
          <div class="weixin-title">
            {{ menuName }}
          </div>
        </div>
        <div class="weixin-menu menu_main clearfix">
          <div class="menu_bottom" v-for="(item, i) of menu" :key="i">
            <!-- 一级菜单 -->
            <div
              @click="menuFun(i, item)"
              class="menu_item el-icon-s-fold"
              :class="{ active: isActive == i }"
            >
              {{ item.name }}
            </div>
            <!--以下为二级菜单-->
            <div class="submenu" v-if="isSubMenuFlag == i">
              <template v-if="item.sub_button">
                <div
                  class="subtitle menu_bottom"
                  v-for="(subItem, k) in item.sub_button"
                  :key="k"
                >
                  <div
                    class="menu_subItem"
                    :class="{ active: isSubMenuActive == i + '' + k }"
                    @click="subMenuFun(subItem, i, k)"
                  >
                    {{ subItem.name }}
                  </div>
                </div>
              </template>
              <!--  二级菜单加号， 当长度 小于  5 才显示二级菜单的加号  -->
              <!-- v-hasPermi="['api:mpManage:addMenu']" -->
              <div
                class="menu_bottom menu_addicon"
                v-if="!item.sub_button || item.sub_button.length < 5"
                @click="addSubMenu(i, item)"
              >
                <!-- <i class="Plus"></i> -->
                <el-icon :size="20">
                  <Plus />
                </el-icon>
              </div>
            </div>
          </div>
          <!-- 一级菜单加号 -->
          <!-- v-hasPermi="['api:mpManage:addMenu']" -->
          <div
            class="menu_bottom menu_addicon"
            v-if="menuKeyLength < 3"
            @click="addMenu"
          >
            <!-- <i class="Plus"></i> -->
            <el-icon :size="20">
              <Plus />
            </el-icon>
          </div>
        </div>
        <!-- v-hasPermi="['api:mpManage:publishMenu']" -->
        <div class="save_div">
          <el-button
            class="save_btn"
            type="success"
            size="small"
            :loading="publishLoading"
            @click="saveAndReleaseFun"
            v-hasPermi="['member:mpMenu:publishMenu']"
            >发布菜单</el-button
          >
          <el-button
            class="save_btn"
            type="primary"
            size="small"
            @click="saveMoreMenu"
            v-hasPermi="['member:mpMenu:saveMoreMenu']"
            >保存菜单</el-button
          >
        </div>
      </div>
      <!--右边配置-->
      <div v-if="showRightFlag" class="right">
        <div class="configure_page">
          <div class="delete_btn">
            <!-- v-hasPermi="['api:mpManage:delMenu']" -->
            <el-button
              type="danger"
              icon="Delete"
              v-hasPermi="['member:mpMenu:del']"
              @click="deleteMenu()"
              >删除当前菜单</el-button
            >
            <!-- v-hasPermi="['api:mpManage:changeMenu', 'api:mpManage:addMenu']" -->
            <el-button
              type="success"
              icon="Check"
              v-hasPermi="['member:mpMenu:add', 'member:mpMenu:change']"
              @click="saveMenu()"
              >保存当前菜单</el-button
            >
          </div>
          <div>
            <el-alert
              title="Notice:一级菜单4个字符，二级菜单8个字符"
              type="error"
            >
            </el-alert>
            <h3></h3>
            <span>菜单名称：</span>
            <el-input
              class="input_width"
              v-model="baseInfo.name"
              placeholder="请输入菜单名称"
              clearable
            ></el-input>
            <!-- 取消长度限制 -->
            <!--  :maxlength="nameMaxlength" -->
          </div>
          <div v-if="showConfigurContent">
            <div class="menu_content">
              <span>菜单内容：</span>
              <el-select
                v-model="baseInfo.type"
                clearable
                placeholder="请选择"
                class="menu_option"
              >
                <el-option
                  v-for="item in menuOptions"
                  :label="item.label"
                  :value="item.value"
                  :key="item.value"
                ></el-option>
              </el-select>
            </div>
            <div class="menu_content">
              <span>系统链接：</span>
              <el-select
                v-model="baseInfo.url"
                clearable
                placeholder="请选择"
                class="menu_option"
              >
                <el-option
                  v-for="item in linkList"
                  :label="item.title"
                  :value="item.url"
                  :key="item.url"
                ></el-option>
              </el-select>
            </div>
            <div class="configur_content" v-if="baseInfo.type == 'view'">
              <el-form :model="baseInfo" ref="baseInfo" :rules="baseInfoRules">
                <el-form-item label="跳转链接：" label-width="100px" prop="url">
                  <el-input
                    class="input_width"
                    v-model="baseInfo.url"
                    placeholder="请输入链接"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-form>
            </div>
            <div class="configur_content" v-if="baseInfo.type == 'keywords'">
              <el-form :model="baseInfo" ref="baseInfo" :rules="baseInfoRules">
                <el-form-item
                  label="关键字："
                  label-width="100px"
                  prop="keywords_id"
                >
                  <el-select
                    filterable
                    clearable
                    v-model="baseInfo.keywords_id"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in keywordsList"
                      :key="item.id"
                      :label="item.keywords"
                      :value="item.id"
                    >
                      <span style="float: left">{{ item.keywords }}</span>
                      <span
                        style="float: right; color: #8492a6; font-size: 13px"
                        >{{
                          item.match_mode == 1 ? "精准匹配" : "包含匹配"
                        }}</span
                      >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
            <div class="configur_content" v-if="baseInfo.type == 'miniprogram'">
              <el-form :model="baseInfo" ref="baseInfo" :rules="baseInfoRules">
                <el-form-item
                  label="小程序的appid："
                  label-width="100px"
                  prop="min_appid"
                >
                  <el-input
                    class="input_width"
                    v-model="baseInfo.min_appid"
                    placeholder="请输入小程序的appid"
                    clearable
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="小程序的页面路径："
                  label-width="100px"
                  prop="page_path"
                >
                  <el-input
                    class="input_width"
                    v-model="baseInfo.page_path"
                    placeholder="请输入小程序的页面路径，如：pages/index"
                    clearable
                  ></el-input>
                </el-form-item>
                <el-form-item label="备用网页：" label-width="100px" prop="url">
                  <el-input
                    class="input_width"
                    v-model="baseInfo.url"
                    placeholder="不支持小程序的老版本客户端将打开本网页"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-form>
              <p class="blue">
                tips:需要和公众号进行关联才可以把小程序绑定带微信菜单上哟！
              </p>
            </div>
            <!-- article_view_limited -->
            <div
              class="configur_content"
              v-if="baseInfo.type == 'view_limited'"
            >
              <el-row>
                <div
                  class="select-item"
                  v-if="
                    baseInfo && baseInfo.content && baseInfo.content.news_item
                  "
                >
                  <WxNews :objData="baseInfo.content.news_item"></WxNews>
                  <el-row class="ope-row">
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      circle
                      @click="deleteTempObj"
                    ></el-button>
                  </el-row>
                </div>
                <div v-if="!baseInfo.content || !baseInfo.content.news_item">
                  <el-row>
                    <el-col :span="24" style="text-align: center">
                      <template
                        v-if="baseInfo.newsItem && baseInfo.newsItem.url"
                      >
                        <div
                          style="
                            width: 100%;
                            display: flex;
                            flex-direction: column;
                            justify-content: center;
                            align-item: center;
                          "
                        >
                          <el-image
                            fit="fill"
                            style="width: 200px; height: 200px; margin: 0 auto"
                            :src="baseInfo.newsItem.thumb_url"
                          >
                          </el-image>
                          <p style="text-align: center">
                            {{ baseInfo.newsItem.title }}
                          </p>
                          <el-form style="margin: 0 auto">
                            <el-form-item label="图文描述" label-width="80px">
                              <el-input
                                style="width: 300px"
                                placeholder="请输入描述"
                                v-model="baseInfo.newsItem.description"
                              ></el-input>
                            </el-form-item>
                          </el-form>

                          <div style="text-align: center; margin-top: 10px">
                            <el-button
                              @click="onDelNews"
                              type="danger"
                              icon="el-icon-delete"
                              circle
                            ></el-button>
                          </div>
                        </div>
                      </template>
                      <el-button v-else type="success" @click="openMaterial"
                        >素材库选择<i
                          class="el-icon-circle-check el-icon--right"
                        ></i
                      ></el-button>
                    </el-col>
                  </el-row>
                </div>
                <el-dialog
                  title="选择图文"
                  v-model:visible="dialogNewsVisible"
                  width="50%"
                >
                  <Material type="news" @onItem="selectMaterial"></Material>
                </el-dialog>
              </el-row>
            </div>
            <div
              class="configur_content"
              v-if="
                baseInfo.type == 'click' || baseInfo.type == 'scancode_waitmsg'
              "
            >
              <template v-if="hackResetWxReplySelect">
                <WxReply :baseInfo="baseInfo"></WxReply>
              </template>
            </div>
          </div>
        </div>
      </div>
      <!--一进页面就显示的默认页面，当点击左边按钮的时候，就不显示了-->
      <div v-if="!showRightFlag" class="right">
        <p>请选择菜单配置</p>
      </div>
    </div>
  </div>
</template>

<script>
import WxNews from "@/cpns/wx-news";
import WxReply from "@/cpns/WxReply";
import Material from "@/cpns/material";
import {
  getList,
  del,
  changeMenu,
  publish,
  addMenu,
  saveMoreMenu,
} from "@/api/mpManage/mpMenu";
import { getKeywordsList } from "@/api/mpManage/mpKeywords";
import { getMpLink } from "@/api/mpManage/mpLink";
import { ElLoading } from "element-plus";
import _ from "lodash";
export default {
  name: "mpmpMenuindex",
  components: { WxNews, Material, WxReply },
  data() {
    return {
      publishLoading: false,
      info: {},
      searchInfo: {
        page: 1,
        page_size: 10,
      },
      baseInfo: {
        newsItem: {
          description: "",
        },
      },
      baseInfoRules: {
        url: [{ required: true, message: "请输入链接", trigger: "blur" }],
        min_appid: [
          { required: true, message: "请输入小程序的appid", trigger: "blur" },
        ],
        keywords_id: [
          { required: true, message: "请选择回复关键字", trigger: "blur" },
        ],
        page_path: [
          {
            required: true,
            message: "请输入小程序的页面路径",
            trigger: "blur",
          },
        ],
      },
      tempSelfObj: {},
      dialogNewsVisible: false,
      showConfigurContent: false,
      nameMaxlength: 0, //一级菜单4个，二级菜单8个
      saveLoading: false,
      showRightFlag: false,
      isSubMenuFlag: -1,
      isSubMenuActive: -1, // 二级菜单点中样式
      isActive: -1,
      menuName: "",
      menu: [],
      menuOptions: [
        {
          value: "keywords",
          label: "关键字",
        },
        {
          value: "view",
          label: "跳转网页",
        },
        {
          value: "miniprogram",
          label: "跳转小程序",
        },
        {
          value: "click",
          label: "点击回复",
        },
        {
          value: "view_limited",
          label: "跳转图文消息",
        },
      ],
      keywordsList: [],
      linkList: [],
    };
  },
  computed: {
    // menuObj的长度，当长度 小于  3 才显示一级菜单的加号
    menuKeyLength: function () {
      return this.menu.length;
    },
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    init() {
      this.getMpLink();
      // this.getInfo();
      this.getAllkeywords();
    },
    async getMpLink() {
      const { data } = await getMpLink();
      this.linkList = data;
      this.getInfo();
    },
    async getAllkeywords() {
      const parasm = {
        page: 1,
        pageSize: 999999999,
      };
      const { data } = await getKeywordsList(parasm);
      this.keywordsList = data.items;
    },
    async getInfo(cb) {
      const { data } = await getList();
      console.log(data);
      this.menu = data;
      cb && cb();
    },
    selectMaterial(item) {
      console.log(item, 999);
      delete item.content;
      // this.baseInfo.newsItem = { ...item };
      // this.$set(this.baseInfo, "newsItem", item);
      this.baseInfo.newsItem = item;
      this.dialogNewsVisible = false;
    },
    onDelNews() {
      // console.log("onDelNews");
      this.baseInfo.newsItem = {
        description: "",
      };
      // this.baseInfo = this.$options.data().baseInfo;
    },
    async saveMoreMenu() {
      const params = { data: this.menu };
      console.log(params);
      // return false;
      saveMoreMenu(params).then((res) => {
        console.log("res", res);
        this.getInfo();
        this.$message.success("操作成功");
      });
    },
    subMenuFun(subItem, index, k) {
      this.hackResetWxReplySelect = false; //销毁组件
      this.$nextTick(() => {
        this.hackResetWxReplySelect = true; //重建组件
      });
      this.showRightFlag = true; //右边菜单
      this.baseInfo = subItem; //将点击的数据放到临时变量，对象有引用作用
      if (subItem.newsItem && typeof subItem.newsItem == "string") {
        this.baseInfo.newsItem = JSON.parse(subItem.newsItem);
      }
      this.baseInfo.msg_type = subItem.msg_type || "text";
      this.tempSelfObj.grand = "2"; //表示二级菜单
      this.tempSelfObj.index = index; //表示一级菜单索引
      this.tempSelfObj.secondIndex = k; //表示二级菜单索引
      this.isSubMenuActive = index + "" + k; //二级菜单选中样式
      this.isActive = -1; //一级菜单去除样式
      this.showConfigurContent = true;
      this.nameMaxlength = 8;
    },
    addMenu() {
      console.log("addMenu");
      // let menuKeyLength = this.menuKeyLength;
      let addButton = {
        name: "菜单名称",
        sub_button: [],
      };
      this.menu.push(addButton);
      this.menuFun(this.menuKeyLength - 1, addButton);
    },
    menuFun(i, item) {
      this.hackResetWxReplySelect = false; //销毁组件
      this.$nextTick(() => {
        this.hackResetWxReplySelect = true; //重建组件
      });
      this.showRightFlag = true; //右边菜单
      this.baseInfo = item;
      if (item.newsItem && typeof item.newsItem == "string") {
        this.baseInfo.newsItem = JSON.parse(item.newsItem);
      }
      this.baseInfo.msg_type = item.msg_type || "text";
      this.tempSelfObj.grand = "1"; //表示一级菜单
      this.tempSelfObj.index = i; //表示一级菜单索引
      this.isActive = i;
      this.isSubMenuFlag = i; //二级菜单显示标志
      this.isSubMenuActive = -1; //二级菜单去除选中样式
      this.nameMaxlength = 5;
      // 存在子菜单是不显示内容
      if (item.sub_button && item.sub_button.length > 0) {
        this.showConfigurContent = false;
      } else {
        this.showConfigurContent = true;
      }
    },
    addSubMenu(i, item) {
      if (!item.sub_button || item.sub_button.length <= 0) {
        // this.$set(item, "sub_button", []);
        item.sub_button = [];
        // this.$delete(item, "type");
        // this.$delete(item, "pagepath");
        // this.$delete(item, "url");
        // this.$delete(item, "key");
        // this.$delete(item, "media_id");
        // this.$delete(item, "textContent");
        this.showConfigurContent = false;
      }
      let subMenuKeyLength = item.sub_button.length; //获取二级菜单key长度
      let addButton = {
        name: "子菜单名称",
        pid: item.id,
      };
      // this.$set(item.sub_button, subMenuKeyLength, addButton);
      item.sub_button[subMenuKeyLength] = addButton;
      this.subMenuFun(item.sub_button[subMenuKeyLength], i, subMenuKeyLength);
    },
    deleteMenu() {
      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (this.baseInfo.id) {
            this.deleteData(); // 删除菜单数据
          } else {
            // 前端编辑未保存删除
            this.baseInfo = {};
            const parentIndex = this.isSubMenuActive[0];
            const childIndex = this.isSubMenuActive[1];
            console.log(childIndex);
            if (childIndex !== undefined) {
              this.menu[parentIndex].sub_button.splice(childIndex, 1);
            } else {
              this.menu.splice(parentIndex, 1);
            }
            console.log(this.menu);
            this.showRightFlag = false;
            this.isActive = -1;
            this.isSubMenuActive = -1;
          }
        })
        .catch(() => {});
    },
    // 删除菜单数据
    async deleteData() {
      const loadingInstance = ElLoading.service({ fullscreen: true });
      try {
        await del(this.baseInfo.id);
      } finally {
        loadingInstance.close();
      }

      this.$message({
        type: "success",
        message: "删除成功!",
      });
      this.getInfo();
      this.baseInfo = {};
      this.showRightFlag = false;
      this.isActive = -1;
      this.isSubMenuActive = -1;
    },
    async saveMenu() {
      console.log(this.baseInfo);
      // return false;
      const cb = () => {
        // isSubMenuActive第一位是一级菜单，第二位是二级菜单
        if (this.isSubMenuActive.length == 2) {
          // 当前是二级菜单
          const curMenuIndex = this.isSubMenuActive[0];
          const curSubIndex = this.isSubMenuActive[1];
          const info = this.menu[curMenuIndex].sub_button[curSubIndex];
          if (info.newsItem) {
            info.newsItem = JSON.parse(info.newsItem);
          }
          // this.baseInfo = info;
          this.baseInfo = _.assign(info, this.baseInfo);
        }
      };
      if (this.$refs.baseInfo) {
        this.$refs.baseInfo.validate(async (valid) => {
          if (valid) {
            console.log(this.baseInfo);
            const params = { ...this.baseInfo };
            // todo 参数需要父子菜单
            console.log(this.menu);
            const loadingInstance = ElLoading.service({ fullscreen: true });
            try {
              if (params.id) {
                await changeMenu(params);
              } else {
                await addMenu(params);
              }
              this.$message.success("保存成功!");
              this.getInfo(cb);
            } finally {
              loadingInstance.close();
            }
          } else {
            console.log("validate error");
          }
        });
      } else {
        // 无表单提交
        const params = { ...this.baseInfo };
        // article_
        if (params.type == "view_limited") {
          if (!this.baseInfo.newsItem) {
            this.$message.error("请选择文章");
            return false;
          }
          // 文章提交
          params.article_id = params.newsItem.article_id;
          params.newsItem = JSON.stringify(params.newsItem);
        }
        if (params.id) {
          await changeMenu(params);
        } else {
          await addMenu(params);
        }
        this.$message.success("保存成功!");
        await this.getInfo(cb);
      }
      // this.showRightFlag = false;
    },
    async saveAndReleaseFun() {
      this.publishLoading = true;
      try {
        await publish();
        this.$message.success("发布成功");
      } finally {
        this.publishLoading = false;
      }
    },
    openMaterial() {
      console.log("openMaterial");
      this.dialogNewsVisible = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.clearfix {
  *zoom: 1;
}
.clearfix::after {
  content: "";
  display: table;
  clear: both;
}
div {
  text-align: left;
}
.weixin-hd {
  color: #fff;
  text-align: center;
  position: relative;
  bottom: 426px;
  left: 0px;
  width: 300px;
  height: 64px;
  background: transparent url(assets/menu_head.png) no-repeat 0 0;
  background-position: 0 0;
  background-size: 100%;
}
.weixin-title {
  color: #fff;
  font-size: 14px;
  width: 100%;
  text-align: center;
  position: absolute;
  top: 33px;
  left: 0px;
}
.weixin-menu {
  background: transparent url(assets/menu_foot.png) no-repeat 0 0;
  padding-left: 43px;
  font-size: 12px;
}
.menu_option {
  width: 40% !important;
}
.public-account-management {
  min-width: 1200px;
  width: 1200px;
  margin: 0 auto;
  .left {
    float: left;
    display: inline-block;
    width: 350px;
    height: 715px;
    background: url("assets/iphone_backImg.png") no-repeat;
    background-size: 100% auto;
    padding: 518px 25px 88px;
    position: relative;
    box-sizing: border-box;
    /*第一级菜单*/
    .menu_main {
      .menu_bottom {
        position: relative;
        float: left;
        display: inline-block;
        box-sizing: border-box;
        width: 85.5px;
        text-align: center;
        border: 1px solid #ebedee;
        background-color: #fff;
        cursor: pointer;
        &.menu_addicon {
          height: 46px;
          line-height: 46px;
        }
        .menu_item {
          height: 44px;
          line-height: 44px;
          text-align: center;
          box-sizing: border-box;
          width: 100%;
          &.active {
            border: 1px solid #2bb673;
          }
        }
        .menu_subItem {
          height: 44px;
          line-height: 44px;
          text-align: center;
          box-sizing: border-box;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          &.active {
            border: 1px solid #2bb673;
          }
        }
      }
      i {
        color: #2bb673;
      }
      /*第二级菜单*/
      .submenu {
        position: absolute;
        width: 85.5px;
        bottom: 45px;
        .subtitle {
          background-color: #fff;
          box-sizing: border-box;
        }
      }
    }
    .save_div {
      margin-top: 15px;
      text-align: center;
      .save_btn {
        // bottom: 20px;
        // left: 100px;
      }
    }
  }
  /*右边菜单内容*/
  .right {
    float: left;
    width: 63%;
    background-color: #e8e7e7;
    padding: 20px;
    margin-left: 20px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    .configure_page {
      .delete_btn {
        text-align: right;
        margin-bottom: 15px;
      }
      .menu_content {
        margin-top: 20px;
      }
      .configur_content {
        margin-top: 20px;
        background-color: #fff;
        padding: 20px 10px;
        border-radius: 5px;
      }
      .blue {
        color: #29b6f6;
        margin-top: 10px;
      }
      .applet {
        margin-bottom: 20px;
        span {
          width: 20%;
        }
      }
      .material {
        .input_width {
          width: 30%;
        }
        .el-textarea {
          width: 80%;
        }
      }
    }
  }
}
.public-account-management {
  .el-input {
    width: 70%;
    margin-right: 2%;
  }
}
.pagination {
  text-align: right;
  margin-right: 25px;
}
.select-item {
  width: 280px;
  padding: 10px;
  margin: 0 auto 10px auto;
  border: 1px solid #eaeaea;
}
.select-item2 {
  padding: 10px;
  margin: 0 auto 10px auto;
  border: 1px solid #eaeaea;
}
.ope-row {
  padding-top: 10px;
  text-align: center;
}
.item-name {
  font-size: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
}
</style>
